<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="券码名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入券码名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cancel:coupon:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleDely"
          v-hasPermi="['cancel:coupon:setOutTime']"
          >批量延期</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleLookAll"
          v-hasPermi="['cancel:coupon:all']"
          >查看全部券码</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cancel:coupon:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="券码名称" align="center" prop="couponName" />
      <el-table-column label="券码金额" align="center" prop="couponPrice" />
      <el-table-column label="券码长度" align="center" prop="couponLen" />
      <el-table-column label="券码生成方式" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.genType == 1">系统生成</div>
          <div v-else-if="scope.row.genType == 2">手动导入</div>
        </template>
      </el-table-column>
      <el-table-column
        label="券码组合类型"
        align="center"
        prop="couponMakeType"
        :formatter="couponMakeTypes"
      />
      <el-table-column label="使用门槛" align="center" prop="cancelPrice" />
      <el-table-column label="发放总量" align="center" prop="sendNum" />
      <el-table-column label="已生成数" align="center" prop="genNum" />
      <el-table-column label="剩余数" align="center" prop="remainNum" />
      <el-table-column label="已使用数" align="center" prop="useNum" />
      <el-table-column
        label="可用开始时间"
        align="center"
        prop="useStartTime"
      />
      <el-table-column label="可用结束时间" align="center" prop="useEndTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cancel:coupon:edit']"
            >修改</el-button
          >
          <div v-if="scope.row.couponType != 3">
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.genType == 1"
              @click="handleGenCode(scope.row)"
              v-hasPermi="['cancel:coupon:genCode']"
              >生成券码</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.genType == 1"
              @click="handleActivate(scope.row)"
              v-hasPermi="['cancel:coupon:genCode']"
              >激活</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-else-if="scope.row.genType == 2"
              @click="handleImport(scope.row)"
              v-hasPermi="['cancel:coupon:genCode']"
              >导入券码</el-button
            >
          </div>

          <el-button
            size="mini"
            type="text"
            @click="handleCodeView(scope.row)"
            v-hasPermi="['cancel:couponCode:codeView']"
            >查看详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.typeWay == 4 || scope.row.typeWay == 8"
            @click="handleGoods(scope.row)"
            v-hasPermi="['cancel:coupon:showCouponProduct']"
            >关联商品</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cancel:coupon:remove']"
            >删除</el-button
          >

          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"

              v-hasPermi="['system:coupon:import']"
            >导入</el-button>
          </el-col> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 生成券码 -->
    <el-dialog
      title="生成券码"
      :rule="rulesGen"
      :visible.sync="isGenCode"
      width="800px"
    >
      <el-form ref="codeForm" :model="codeForm" label-width="100px">
        <el-form-item label="券码名称" prop="couponName">
          <el-input
            v-model="codeForm.couponName"
            disabled
            placeholder="请输入券码名称"
          />
        </el-form-item>
        <el-form-item label="可兑换商品数" prop="number">
          <el-input
            v-model="codeForm.number"
            placeholder="请输入可兑换商品数"
          ></el-input>
        </el-form-item>

        <el-form-item label="券码长度" prop="couponLen">
          <el-input
            type="number"
            v-model="codeForm.couponLen"
            placeholder="请输入券码长度"
          />
        </el-form-item>
        <el-form-item label="券码组合类型" prop="couponMakeType">
          <el-radio-group v-model="codeForm.couponMakeType">
            <el-radio :label="1">字母加数字</el-radio>
            <!-- <el-radio :label="2">纯字母</el-radio>
            <el-radio :label="3">纯数字</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放数量" prop="genNum">
          <!-- <el-input v-model="form.sendNum" placeholder="请输入发放数量" /> -->
          <el-input-number
            v-model="codeForm.genNum"
            :min="1"
            :max="codeForm.sendNum"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="使用门槛"
          prop="cancelPrice"
          v-if="codeForm.typeWay != 4"
        >
          <el-input
            type="number"
            v-model.number="codeForm.cancelPrice"
            placeholder="请输入使用金额门槛"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="isGenCode = false">取 消</el-button>
        <el-button :loading="genLoad" type="primary" @click="subGenCode"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 激活 -->
    <el-dialog title="激活券码" :visible.sync="isActived" width="800px">
      <el-form
        ref="activedForm"
        :model="activedForm"
        :rules="activedRule"
        label-width="100px"
        style="width: 60%"
      >
        <el-form-item label="序号区间" prop="startNum">
          <el-col :span="11">
            <el-form-item prop="startNum">
              <el-input
                v-model.number="activedForm.startNum"
                oninput="value=value.replace(/[^\d]/g,'')"
                placeholder=""
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endNum">
              <el-input
                v-model.number="activedForm.endNum"
                oninput="value=value.replace(/[^\d]/g,'')"
                placeholder=""
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="券码状态" prop="isStatus">
          <el-radio-group v-model="activedForm.isStatus">
            <el-radio :label="0">未激活</el-radio>
            <el-radio :label="1">已激活</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="过期时间" prop="outTime">
          <el-date-picker
            v-model="activedForm.outTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择过期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="isActived = false">取 消</el-button>
        <el-button type="primary" @click="subActive">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改券码管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        style="width: 80%"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="券码名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入券码名称" />
        </el-form-item>
        <el-form-item label="所属客户" prop="customerId">
          <el-select
            v-model="form.customerId"
            @change="getMallList"
            placeholder="请选择"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属商城" prop="mallId">
          <el-select v-model="form.mallId" placeholder="请选择">
            <el-option
              v-for="item in mallList"
              :key="item.id"
              :label="item.mallName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="券码金额" prop="couponPrice">
          <el-input-number
            v-model="form.couponPrice"
            :precision="2"
            :min="0.01"
            :max="1000000"
            @change="getBuyPriceNum"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="发放数量" prop="sendNum">
          <!-- <el-input v-model="form.sendNum" placeholder="请输入发放数量" /> -->
          <el-input-number
            v-model="form.sendNum"
            :min="1"
            @change="getBuyPriceNum"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="采购金额" prop="buyPrice">
          <el-input v-model="form.buyPrice" readonly style="width: 200px" />
        </el-form-item>
        <el-form-item label="券码类型" prop="couponType">
          <el-radio-group v-model="form.couponType" :disabled="isXiugai">
            <el-radio :label="2">线上兑换</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="核销方式" prop="typeWay">
          <el-radio-group v-model="form.typeWay" :disabled="isXiugai">
            <el-radio :label="1" v-hasPermi="['system:coupon:points']"
              >积分</el-radio
            >
            <!-- <el-radio :label="2">余额</el-radio>
            <el-radio :label="3">优惠券</el-radio> -->
            <el-radio :label="4" v-hasPermi="['system:coupon:toGoods']"
              >指定商品优惠券</el-radio
            >
            <el-radio :label="8" v-hasPermi="['system:coupon:toGoods']"
              >指定商品满减优惠券</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="券码生成方式" prop="genType">
          <el-radio-group v-model="form.genType" :disabled="isXiugai">
            <el-radio :label="1">系统生成</el-radio>
            <!-- <el-radio :label="2">余额</el-radio>
            <el-radio :label="3">优惠券</el-radio> -->
            <el-radio :label="2">手动导入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="可用开始时间"
          prop="useStartTime"
          v-if="form.couponType != 3"
        >
          <el-date-picker
            v-model="form.useStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择可用开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="可用结束时间"
          prop="useEndTime"
          v-if="form.couponType != 3"
        >
          <el-date-picker
            v-model="form.useEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择可用结束时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量延期 -->
    <el-dialog
      title="延期"
      :visible.sync="delyOpen"
      width="400px"
      append-to-body
    >
      <el-form
        ref="dely"
        :model="delyForm"
        :rules="delyRules"
        label-width="80px"
      >
        <el-form-item label="延期到" prop="useEndTime">
          <el-date-picker
            v-model="delyForm.useEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择延期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDely">确 定</el-button>
        <el-button @click="delyOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&couponId=' +
          couponId
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" />-->
          <!--            是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 关联商品 -->
    <related-goods
      :openGoods.sync="openGoods"
      @close="closeGoods"
      @getGoodsList="getGoods"
      :selectedProductList.sync="selectedProductList"
    ></related-goods>
  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
  genCode,
  jhCoupon,
  setCouponGoods,
  goodsListInfo,
  showProductVirList,
  showShoperList,
  setOutTime,
  getCustomerShopList,
} from "@/api/system/coupon";
import { listAllCustomer } from "@/api/customer/employee";
import RelatedGoods from "../../components/relatedGoods.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "Coupon",
  components: {
    RelatedGoods,
  },
  data() {
    const numberValidate = (rule, value, callback) => {
      if (value < 8) {
        callback(new Error(rule.message));
      } else if (value > 16) {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    };
    return {
      // 延期
      delyOpen: false,
      delyForm: {},
      //是否展示关联商品
      openGoods: false,
      isGenCode: false,
      isActived: false,
      genLoad: false,
      //是否可编辑
      isXiugai: false,
      // 遮罩层
      loading: true,
      customerList: [],
      //商城列表
      mallList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 券码管理表格数据
      couponList: [],
      shoperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/cancel/coupon/importDataVir",
      },
      //导入券码传入的id
      couponId: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponName: null,
        couponType: 2,
      },
      //关联商品列表
      productList: [],
      // 表单参数
      form: {},
      //生成券码
      codeForm: {},
      //激活券码
      activedForm: {},
      // 表单校验
      rules: {
        couponName: [
          { required: true, message: "券码名称不能为空", trigger: "blur" },
        ],
        mallProductId: [
          { required: true, message: "请选择关联商品", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "请选择所属客户", trigger: "change" },
        ],
        mallId: [
          { required: true, message: "请选择所属商城", trigger: "change" },
        ],
        couponPrice: [
          { required: true, message: "券码金额不能为空", trigger: "blur" },
        ],
        sendNum: [
          { required: true, message: "发放数量不能为空", trigger: "blur" },
        ],
        buyPrice: [
          { required: true, message: "采购金额不能为空", trigger: "blur" },
        ],
        couponType: [
          { required: true, message: "请选择券码类型", trigger: "blur" },
        ],
        typeWay: [
          { required: true, message: "请选择核销方式", trigger: "blur" },
        ],
        genType: [
          { required: true, message: "请选择券码生成方式", trigger: "blur" },
        ],

        useStartTime: [
          { required: true, message: "可用开始时间不能为空", trigger: "blur" },
        ],
        useEndTime: [
          { required: true, message: "可用结束时间不能为空", trigger: "blur" },
        ],
      },
      rulesGen: {
        number: [
          { required: true, message: "请输入指定商品数量", trigger: "blur" },
        ],

        couponLen: [
          { required: true, message: "券码长度不能为空", trigger: "blur" },
          {
            validator: numberValidate,
            trigger: "blur",
            message: "券码长度应为8-16之间",
          },
        ],
        couponMakeType: [
          { required: true, message: "请选择券码组合类型", trigger: "blur" },
        ],
        cancelPrice: [
          { required: true, message: "使用门槛不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("使用门槛不得小于0元"));
              } else if (value >= 10000000000) {
                return callback(new Error("使用门槛不得大于10位"));
              } else {
                return callback();
              }
            },
          },
        ],
      },
      activedRule: {
        startNum: [
          { required: true, message: "序号区间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              return callback();
            },
          },
        ],
        endNum: [
          { required: true, message: "序号区间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              return callback();
            },
          },
        ],
        isStatus: [
          { required: true, message: "请选择券码状态", trigger: "change" },
        ],
        outTime: [
          { required: true, message: "请选择过期时间", trigger: "blur" },
        ],
      },
      delyRules: {
        useEndTime: [
          { required: true, message: "请选择延期时间", trigger: "blur" },
        ],
      },
      selectedProductList: [],
    };
  },
  created() {
    this.getList();
    this.getAllCustomerList();
  },
  methods: {
    couponMakeTypes(row, column, cellValue) {
      if (cellValue == "1") {
        return "字母加数字";
      } else if (cellValue == "2") {
        return "纯字母";
      } else {
        return "纯数字";
      }
    },
    getBuyPriceNum() {
      const totalNum = this.form.couponPrice * this.form.sendNum;
      totalNum > 0
        ? (this.form.buyPrice = totalNum)
        : (this.form.buyPrice = 0.01);
    },
    //获取商城列表
    getMallList(value) {
      getCustomerShopList({ customerId: value }).then((res) => {
        this.mallList = res.data;
      });
    },
    //获取关联商户列表
    getShoperList() {
      showShoperList().then((res) => {
        this.shoperList = res.data;
      });
    },
    // 查询所有客户列表
    getAllCustomerList() {
      listAllCustomer().then((res) => {
        this.customerList = res.data;
      });
    },
    //获取关联商品列表
    getProductList() {
      showProductVirList().then((res) => {
        this.productList = res.data;
        this.productList = res.data;
      });
    },
    //提交关联商品
    getGoods(e) {
      console.log(e);
      const data = {
        catId: e.oneCategoryId,
        oneCatId: e.twoCategoryId,
        twoCatId: e.threeCategoryId,
        threeCatId: null,
        couponId: this.couponId,
      };
      data.goodsIdArs = e.goodsIdArs.map((v) => v.productId);
      setCouponGoods(data).then((res) => {
        this.$message({
          message: res.msg,
          type: "success",
        });
        this.openGoods = false;
      });
    },

    // 打开关联商品
    handleGoods(row) {
      this.couponId = row.id;
      this.openGoods = true;
      this.getSelectGoods();
    },
    getSelectGoods() {
      goodsListInfo({ couponId: this.couponId }).then((res) => {
        this.selectedProductList = res.data;
      });
    },

    //关闭商品列表
    closeGoods(e) {
      this.openGoods = false;
    },

    /** 查询券码管理列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then((response) => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        couponName: null,
        number: 1,
        couponPrice: null,
        couponLen: 16,
        couponMakeType: 1,
        cancelPrice: null,
        couponType: 2,
        sendNum: null,
        goodsCateArs: null,
        goodsIdArs: null,
        useStartTime: null,
        useEndTime: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 批量延期
    handleDely() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要延期的券码");
      } else {
        this.delyOpen = true;
      }
    },
    submitDely() {
      this.$refs["dely"].validate((valid) => {
        if (valid) {
          const data = {
            ...this.delyForm,
            couponIds: this.ids.join(","),
          };
          setOutTime(data).then((res) => {
            this.$modal.msgSuccess("延期成功");
            this.delyOpen = false;
            this.getList();
          });
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**生成券码 */
    handleGenCode(row) {
      console.log(row);
      this.isGenCode = true;
      this.codeForm = { ...row, genNum: row.remainNum };
    },
    // 激活券码
    handleActivate(row) {
      console.log(row);
      this.activedForm = {
        cid: row.id,
        startNum: null,
        endNum: null,
        outTime: row.useEndTime,
        isStatus: 1,
      };
      this.isActived = true;
    },
    // 查看全部券码
    handleLookAll() {
      this.$router.push({
        path: "/coupon/allCode",
      });
    },
    /**查看券码详情 */
    handleCodeView(row) {
      console;
      this.$router.push({
        path: "/coupon/codeView",
        query: {
          cid: row.id,
          couponType: row.couponType,
        },
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isXiugai = false;
      this.title = "添加券码管理";
      this.getProductList();
      this.getShoperList();
      this.getBuyPriceNum();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getProductList();
      this.getShoperList();
      this.getBuyPriceNum();
      this.isXiugai = true;
      const id = row.id || this.ids;
      getCoupon(id).then((response) => {
        this.getMallList({ customerId: response.data.customerId });
        this.form = response.data;
        this.open = true;
        this.title = "修改券码管理";
      });
    },
    // 提交生成券码
    subGenCode() {
      this.genLoad = true;
      this.$refs["codeForm"].validate((valid) => {
        if (valid) {
          genCode(this.codeForm)
            .then((res) => {
              let _this = this;
              this.$alert(res.msg, "提示", {
                confirmButtonText: "确定",
                callback: () => {
                  _this.getList();
                },
              });
              _this.isGenCode = false;
              _this.genLoad = false;
            })
            .catch((err) => {
              this.genLoad = false;
            });
        }
      });
    },
    subActive() {
      this.$refs["activedForm"].validate((valid) => {
        if (valid) {
          jhCoupon(this.activedForm).then((res) => {
            this.$modal.msgSuccess("激活成功");
            this.isActived = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupon(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const couponName = row.couponName;
      this.$modal
        .confirm("是否确认删除" + couponName + "？")
        .then(function () {
          return delCoupon(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/coupon/export",
        {
          ...this.queryParams,
        },
        `coupon_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport(row) {
      const { id } = row;
      this.couponId = id;
      this.upload.title = "导入券码";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "cancel/coupon/importTemplateOnline",
        { couponId: this.couponId },
        `coupon_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
